13. Exercise: Refresh Data with DiffUtil
L7 21 DiffUtil SC
Now it’s your turn to complete this exercise yourself.
In this step you'll take the Adapter you finished in the last section and add DiffUtils to calculate changes when the list changes.
When you've completed this exercise you will have refactored the SleepNightAdapter to use ListAdapter, and replaced notifyDataSetChanced with the more optimized DiffUtil.
At the bottom of
SleepNightAdapter.kt, create a new classSleepNightDiffCallbackthat extendsDiffUtil.ItemCallback<SleepNight>.class SleepNightDiffCallback : DiffUtil.ItemCallback<SleepNight>() { }In
SleepNightDiffCallbackoverrideareItemsTheSame.Two items are the same if their
nightIdvalues are equal.
Override
areContentsTheSameinSleepNightDiffCallback.Two items are the same if they have the same value,
oldItem == newItem.
Update
SleepNightAdapterto extendListAdapterwith aSleepNightDiffCallback()parameter:class SleepNightAdapter : ListAdapter<SleepNight, SleepNightAdapter.ViewHolder>(SleepNightDiffCallback())Make sure to import
ListAdapterfromandroidx.recyclerview.widget.ListAdapter.
Delete the data field and getItemCount().
Remove the code for
val dataandgetItemCount.NOTE: Your code will not compile after this step. We'll fix that in the next few steps.
In
onBindViewHolder()replacedata[position]with a call togetItem().
In
SleepTrackerFragmentnightsobserver, replaceadapter.dataassignment with a call toadapter.submitList().
Run the app again! You should see the items animate when you start a sleep night.
If you want to start at this step, you can download this exercise from: Step.07-Exercise-Add-DiffUtil-to-Adaptera.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here: Step.07-Solution-Add-DiffUtil-to-Adapter, or using this git diff.
Task Description:
Complete these tasks to implement DiffUtil to calculate changes when the list changes.
Task Feedback:
Great job! Add a few items to see RecyclerView animate the changes!
Reference Documentation